
package com.stylefeng.guns.modular.huamao.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.catalina.startup.UserDatabase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.util.MD5Util;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.huamao.dao.AccountMapper;
import com.stylefeng.guns.modular.huamao.dao.SktAgentsStockholderMapper;
import com.stylefeng.guns.modular.huamao.dao.SktLogUsersLoginsMapper;
import com.stylefeng.guns.modular.huamao.dao.UsersMapper;
import com.stylefeng.guns.modular.huamao.model.Account;
import com.stylefeng.guns.modular.huamao.model.DownShop;
import com.stylefeng.guns.modular.huamao.model.SktLogUsersLogins;
import com.stylefeng.guns.modular.huamao.model.UserIdentity;
import com.stylefeng.guns.modular.huamao.model.Users;
import com.stylefeng.guns.modular.huamao.model.UsersDTO;
import com.stylefeng.guns.modular.huamao.model.UsersLoginDTO;
import com.stylefeng.guns.modular.huamao.service.IAccountService;
import com.stylefeng.guns.modular.huamao.service.IUsersService;



/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author slt123
 * @since 2018-04-10
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {
	@Autowired
	private UsersMapper usersMapper;
	@Autowired
	private SktLogUsersLoginsMapper sktLogUsersLoginsMapper;
	@Autowired
	private AccountMapper accountMapper;
	@Autowired
	private SktAgentsStockholderMapper sktAgentsStockholderMapper;
	@Autowired
	IAccountService accountService;

	private static final String REPEAT_LOGIN_NAME = "REPEAT_NAME";//登录名重复
	private static final String REPEAT_LOGIN_PHONE = "REPEAT_PHONE";//用户电话重复
	private static final String SUCCESS = "SUCCESS";
	private static final String SLAT = "ssts3";
	private final Integer COUNT = 9;
	private final String REPEAT = "REPEAT";
	@Override
	public List<UsersDTO> selectUsersInfo(UsersDTO usersDTO) {
		List<UsersDTO> list = usersMapper.selectUsersInfo(usersDTO);
		return list;
	}

	@Override
	public UsersDTO selectOneUsersInfo(UsersDTO usersDTO) {
		
		
		return usersMapper.selectOneUsersInfo(usersDTO);
	}

	@Override
	public List<UsersDTO> selectTuiUsersInfo(Integer inviteId) {
		List<UsersDTO> list = usersMapper.selectTuiUsersInfo(inviteId);
		return list;
	}

	@Override
	public String updateUsersInfo(UsersDTO usersDTO) {
		Users user = new Users();
		user.setUserId(usersDTO.getUserId());
		user.setUserPhoto(usersDTO.getUserPhoto());
		Integer updateById = usersMapper.updateById(user);
		return updateById != 0 ? "1": "0";
	}

	@Override
	public Users selectTuiUsersName(Users users) {
		Users users2 = usersMapper.selectOne(users);
		return users2;
	}
	@Override
	public int selectCount() {
		// TODO Auto-generated method stub
		return usersMapper.selectCount();
	}
	@Override
	public int getTotal() {
		// TODO Auto-generated method stub
		return usersMapper.getTotal();
	}
	
	@Override
	public Map<String,Object> selectUsersPhone(Users users) {
		Map<String,Object> user = usersMapper.selectUsersPhone(users);
		return user;
	}
	@Override
	public UsersLoginDTO userLogin(Users users,String ip) {
		Users users2 = usersMapper.selectByUserInfo(users);
		if(users2 == null){
			return new UsersLoginDTO();
		}
		System.out.println(users.getLoginPwd()+users2.getLoginSecret());
		String salt = MD5Util.encrypt(users.getLoginPwd()+users2.getLoginSecret());
		if(!(users2.getLoginPwd().equals(salt))){//判断密码是否一致
			return new UsersLoginDTO();
		}
		String ss = MD5Util.encrypt(users.getLoginPwd()+users2.getLoginSecret());
		users.setLoginPwd(ss);
		UsersLoginDTO user = usersMapper.userLogin(users);

		SktLogUsersLogins sktLogUsersLogins = new SktLogUsersLogins();
		sktLogUsersLogins.setLoginTime(new Date());
		sktLogUsersLogins.setLoginIp(ip);
		sktLogUsersLogins.setUserId(user.getUserId());
		sktLogUsersLogins.setLoginTer(1);
		sktLogUsersLoginsMapper.insert(sktLogUsersLogins);
		
		return user;
	}
	@Override
	public Users checkUserPhoneOrloginName(String userPhoneOrloginName) {
		return usersMapper.checkUserInfo(userPhoneOrloginName);
	}
	@Override
    public Map<String, Object> selectUsersUpLevel(Integer id) {
        Users users = usersMapper.selectById(id);
        Map<String,Object> mapUp = new HashMap<>();
        if(users.getInviteId() == null && users.getInviteId() == 0){
            return mapUp;
        }

        StringBuffer sb = new StringBuffer();
        int num = 0;
        selectUp(sb,users.getInviteId(),num);
        mapUp.put("upUser",users.getInviteId());
        mapUp.put("upUsers",sb);

        return mapUp;
    }
	public void selectUp(StringBuffer sb, Integer userId, Integer num){
        Users users = usersMapper.selectById(userId);
        Integer userIds = users.getInviteId();
        if(userIds != 0 &&  num < COUNT){
            num++;
            sb.append(userIds).append(",");
            selectUp(sb,userIds,num);
        }
	}
	
	@Override
    public Map<String,Object> selectByUsersInfo(Integer id) {
        Map<String,Object> userMap = usersMapper.selectByUsersInfo(id);
        return userMap;
    }
	
	@Override
	public int updateUsersPwd(UsersDTO users) {
		int i = 0;
		Integer userId = users.getUserId();
		Users user = usersMapper.selectById(userId);
		String sPwd = MD5Util.encrypt(users.getLoginPwd()+user.getLoginSecret());
		if(user.getLoginPwd().equals(sPwd)){
			String newPwd = MD5Util.encrypt(users.getNewLoginPwd()+user.getLoginSecret());
			users.setNewLoginPwd(newPwd);
			i = usersMapper.updateUsersPwd(users);
		}
		return i;
	}
	@Transactional
	@Override
	public String insertUsers(Users users) {
		 //查询用户名、电话号是否重复
		try{
			List<Users> user = usersMapper.selectByLoginName(users.getLoginName(),users.getUserPhone());
			if(user.size()>0){
				return REPEAT;
			}
			Random random = new Random();
			int a = random.nextInt(9000) + 1000;
			users.setUserType(0);
			users.setIsPrivilege(0);
			users.setUserStatus(1);
			users.setCreateTime(new Date());
			System.out.println(users.getLoginPwd()+a);
			users.setLoginPwd(MD5Util.encrypt(users.getLoginPwd()+a));
			users.setLoginSecret(a);
			Integer str = usersMapper.insert(users);
			List<Users> usersList= usersMapper.selectByLoginName(users.getLoginName(),users.getUserPhone());
			Users users2=new Users();
			if (usersList!=null && usersList.size()>0){
				users2=usersList.get(0);
			}
			Account account=new Account();
			account.setUserId(users2.getUserId());
			account.setShopId(0);
			account.setCreateTime(new Date());
			accountMapper.insert(account);
			return str.toString();
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "0";
		}


	}
	@Override
	public List<Integer> getIds(Integer userId){
		List<Integer> list=new ArrayList<>();
		Users user = usersMapper.selectById(userId);
		if(user!=null){
			int InviteId=user.getInviteId();
			if (InviteId!=0){
				for (int i=0;i<10;i++){
					Users user1 = usersMapper.selectById(InviteId);
					if(user1.getInviteId()==0){
						break;
					}else{
						list.add(user1.getInviteId());
						InviteId=user1.getInviteId();
					}
				}
			}
		}
		return list;
	}

	@Override
	public Integer upStauts(Users users) {
		Integer stauts = usersMapper.upStauts(users);
		return stauts;
	}

	@Override
	public UserIdentity userIdentity(Integer id) {
		UserIdentity userIdentity = usersMapper.userIdentity(id);
		return userIdentity;
	}

	@Override
	public int updateUsersPayPwd(UsersDTO users) {
		int i = 0;
		Integer userId = users.getUserId();
		Users user = usersMapper.selectById(userId);
		String newPwd = MD5Util.encrypt(users.getNewLoginPwd()+user.getLoginSecret());
		users.setNewLoginPwd(newPwd);
		i = usersMapper.updateUsersPayPwd(users);
		return i;
	}

	@Override
	public Integer developmentUser(Users users) {
		Integer count = usersMapper.developmentUser(users);
		return count;
	}

	/**
	 * 支付时判断支付密码
	 * @param userId
	 * @param payPwd
	 * @return
	 */
	@Override
	public JSONObject checkPayPassWorld(Integer userId,String payPwd){
		JSONObject json = new JSONObject();

		Users user = usersMapper.selectById(userId);
		String pPwd = MD5Util.encrypt(payPwd+user.getLoginSecret());
		if (user.getPayPwd()==null){
			json.put("code","00");
			json.put("msg","请设置支付密码");
			return  json;
		}
		if ("".equals(payPwd) ||payPwd==null){
			json.put("code","00");
			json.put("msg","请输入支付密码");
			return  json;
		}
		if (pPwd.equals(user.getPayPwd())){
				json.put("code","01");
			//	json.put("msg","下单成功");
		}else {
			json.put("code","00");
			json.put("msg","支付密码错误，请重新输入");
		}
		return  json;
	}
	@Override
	public int findUsersPwd(UsersDTO users) {
		//查找安全码
		Users user = usersMapper.selectUserByPhone(users.getUserPhone());
		if(ToolUtil.isEmpty(user)){
			return 0;
		}
		//MD5加密
		Integer loginSecret = user.getLoginSecret();
		String newPwd = MD5Util.encrypt(users.getNewLoginPwd()+loginSecret);
		user.setLoginPwd(newPwd);
		Integer updateById = usersMapper.updateById(user);
		return updateById;
	}


	//=========================app接口

	/**
	 * 查询用户账户
	 * @param userId
	 * @return
	 */
	@Override
	public DownShop appFindUserById(Integer userId) {
		DownShop downShop = usersMapper.appFindUserById(userId);
		if(downShop != null){
			//如果downShop.getIsAgent()不为0说明为股东
			if(downShop.getIsAgent() != 0){
				//查询累计分红
				BigDecimal totalDividend = sktAgentsStockholderMapper.selectTotalDividend(userId);
				downShop.setTotalDividendScore(totalDividend);
			}
		}
		return downShop;
	}

	@Override
	public Map<String, Object> selectIdLoginNameShareInfo(String afterValue) {
		Map<String,Object> map = usersMapper.selectIdLoginNameShareInfo(afterValue);
		return map;
	}

	
}

